package com.mar.framecompress;

import java.nio.ByteBuffer;

public class CompositeEncoder implements IEncoder {
	//TODO: verify const!
	private static final int DEFAULT_CAPACITY = 2*1024*1024*4;
	private final IEncoder[] encoders;
	private final ByteBuffer intermideateBuffer = ByteBuffer.allocate(DEFAULT_CAPACITY);
	
	// TODO: follow convention: at least 1 encoder should be specified
	public CompositeEncoder( IEncoder... encoders ){
		this.encoders = encoders;
	}
	
	public void encode(ByteBuffer inBuff, ByteBuffer outBuff) {
		ByteBuffer[] availableBuffers = new ByteBuffer[2];
		if ( encoders.length % 2 == 0 ){
			availableBuffers[0] = intermideateBuffer;
			availableBuffers[1] = outBuff;
		} else {
			availableBuffers[0] = outBuff;
			availableBuffers[1] = intermideateBuffer;
		}
		
		ByteBuffer currentIn = inBuff;
		ByteBuffer currentOut = availableBuffers[0];
		final int actualOutBufferLimit = Math.min( outBuff.limit() , intermideateBuffer.limit());
		
		for (int i = 0 ; i < encoders.length; i++ ){
			currentOut.limit(actualOutBufferLimit);
			encoders[i].encode(currentIn, currentOut);
//			currentIn.flip();
//			currentOut.flip();
			
			currentIn = availableBuffers[ i % 2 ];
			currentOut = availableBuffers[ (i+1) % 2 ];
		}
		
		intermideateBuffer.clear();
	}

}
